import { ReactNode, useState } from "react";
import { Todo } from "./interface";
import { useTasks, useTasksDispatch } from "./TasksContext";
import { CHANGE_TODO, DELETE_TODO } from "./action";

interface TaskProps {
  todo: Todo;
}
function Task({ todo }: TaskProps) {
  const [isEditing, setIsEditing] = useState(false);
  const dispatch = useTasksDispatch();

  const onChange = (nextTodo: Todo) => {
    dispatch !== null &&
      dispatch({
        type: CHANGE_TODO,
        payload: {
          todo: nextTodo
        }
      });
  };

  const onDelete = (todoId: number) => {
    dispatch !== null &&
      dispatch({
        type: DELETE_TODO,
        payload: {
          id: todoId
        }
      });
  };

  let todoContent: ReactNode;
  if (isEditing) {
    todoContent = (
      <>
        <input
          value={todo.title}
          onChange={e => {
            onChange({ ...todo, title: e.target.value });
          }}
        />
        &nbsp;
        <button onClick={() => setIsEditing(false)}>保存</button>
      </>
    );
  } else {
    todoContent = (
      <>
        {todo.title}
        &nbsp;
        <button onClick={() => setIsEditing(true)}>编辑</button>
      </>
    );
  }

  return (
    <label>
      <input
        type="checkbox"
        checked={todo.done}
        onChange={e => {
          onChange({ ...todo, done: e.target.checked });
        }}
      />
      {todoContent}
      &nbsp;
      <button onClick={() => onDelete(todo.id)}>删除</button>
    </label>
  );
}

function TaskList() {
  const todos = useTasks();
  return (
    <ul>
      {todos?.map(todo => (
        <li key={todo.id}>
          <Task todo={todo} />
        </li>
      ))}
    </ul>
  );
}

export default TaskList;
